#!/bin/sh /etc/rc.common

#
# Copyright (C) 2020-2022  sirpdboy  <herboy2008@gmail.com> https://github.com/sirpdboy/netspeedtest

# This is free software, licensed under the Apache License, Version 2.0 .
#

START=99
USE_PROCD=1


PROG=/usr/bin/homebox
EXTRA_COMMANDS="nstest"

TMP_T=/var/netspeedtest.tmp
LOCK=/var/lock/netspeedtest.lock
LOG=/var/log/netspeedtest.log

limit_log() {
	local logf=$1
	[ ! -f "$logf" ] && return
	local sc=100
	[ -n "$2" ] && sc=$2
	local count=$(grep -c "" $logf)
	if [ $count -gt $sc ];then
		let count=count-$sc
		sed -i "1,$count d" $logf
	fi
}

init_env() {
	[ ! -f "$LOG" ] && echo "" > $LOG
	echo 1 > $TMP_T

}

nstest() {
    [ -f $LOCK ] && exit
    limit_log $LOG 200
    init_env
    touch $LOCK
    
    echo -ne "\n  speedtest测速"       | tee -a $LOG
    /usr/bin/speedtest --share  > $TMP_T
    echo -ne  "\n  测服信息:$(cat  $TMP_T | grep 'Hosted by'| cut -c10- | awk -F: '{printf $1}')  延时：$(cat  $TMP_T | grep 'Hosted by' | awk -F: '{printf $2}')" >> $LOG
    echo -ne "\n  下行速率:$(cat  $TMP_T  | grep 'Download:' |awk -F: '{printf $2}' )"   >> $LOG
    echo -ne "  ----  上行速率:$(cat  $TMP_T  | grep 'Upload:' |awk -F: '{printf $2}' )"  >> $LOG
    echo -ne "\n  测试时间: "  >> $LOG
    echo $(date +%Y-%m-%d" "%H:%M:%S)  >> $LOG
    echo -ne "  ————————————————————————————\n"  >> $LOG
    echo -ne $(cat  $TMP_T  | grep 'results:' | cut -c16- )
    rm -f $LOCK
}

get_config() {
        config_get_bool enabled $1 enabled 1
	config_get_bool logger $1 logger 1
}

homebox_prepare() {
	pgrep -f homebox | xargs kill -9 >/dev/null 2>&1 
}

stop_service() {
	# homebox_prepare
	echo "homebox stop"
}

start_service() {
	homebox_prepare
	config_load netspeedtest
        config_foreach get_config homebox
	[ "x$enabled" == "x1" ] || return 1
	procd_open_instance
	procd_set_param command $PROG
	[ "x$logger" == x1 ] && procd_set_param stderr 1
	procd_set_param respawn
	procd_close_instance
}

service_triggers() {
      procd_add_reload_trigger "netspeedtest"
}

